package cn.youyu.fm.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: mayuanbao
 * @date: 2018-12-04 21:26
 * @description:
 */
@Controller
@RequestMapping(value = "/login")
public class LoginController {
    @RequestMapping(value = "/index")
    public String login() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            return "/index";
        }
        return "/login/index";
    }

    @RequestMapping(value = "/dologin", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> dologin(HttpServletRequest req) {
        String name = req.getParameter("username");
        String pwd = req.getParameter("password");
        Map<String, Object> data = new HashMap<>();
        if (name.equals("")) {
            data.put("code", 1);
            data.put("msg" , "用户名不能为空");
            return data;
        }
        if (pwd.equals("")) {
            data.put("code", 1);
            data.put("msg" , "密码不能为空");
            return data;
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(name, pwd);
        try {
            subject.login(token);
        } catch (UnknownAccountException | IncorrectCredentialsException uae) {
            data.put("code", 1);
            data.put("msg" , "用户名或密码错误");
            return data;
        } catch (LockedAccountException lae) {
            data.put("code", 1);
            data.put("msg","用户已被锁定");
            return data;
        } catch (ExcessiveAttemptsException eae) {
            data.put("code", 1);
            data.put("msg", "登录失败次数过多");
            return data;
        } catch (AuthenticationException ae) {
            data.put("code", 1);
            data.put("msg", ae.getMessage().equals("用户已停用") ? "用户已停用" : "登录失败，请联系管理员");
            return data;
        }
        if (subject.isAuthenticated()) {
            data.put("code", 0);
            data.put("msg", "登录成功");
            return data;
        }
        return null;
    }
}
